<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/7
 * Time: 14:45
 */

namespace app\controllers;

use yii;
use yii\web\Controller;
use app\lib\Base;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class ApiBaseController extends Controller
{
    use Base;

    public $enableCsrfValidation = false;

    public $user;

    public function beforeAction($action)
    {
        if (!$jwt = $this->getToken()) {
            $this->redirect('/login/index');
            return false;
        }
        $token = (new Parser())->parse($jwt);
        $expire = $token->getClaim('expire_time');
        //token验证 和过期验证
        if (!$token->verify((new Sha256()), yii::$app->params['jwt_token']) || time() > $expire) {
            echo json_encode(['code' => 401, 'msg' => '认证过期']);
            return false;
        }
        $this->user = $this->currentUser();
        return parent::beforeAction($action);
    }

    /**获取excel对象
     * @param $file_path
     * @param $ext
     * @return \PHPExcel
     * @throws \PHPExcel_Reader_Exception
     */
    public function get_excel($file_path, $ext)
    {
        if ($ext == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($file_path, 'utf-8');
        } elseif ($ext == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($file_path, 'utf-8');
        }

        return $objPHPExcel;
    }

}